/**
 *
 */
package com.dchh.android.suverynew.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.act.MyDemandActivity;
import com.dchh.android.suverynew.adapter.MyPagerAdapter;
import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.common.bean.Item;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.MyViewPager;
import com.dhcc.android.base.common.view.ScrollViewCustom;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.DemandDKMapUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import srs.tools.MapControl;

/**
 * 可扩展的page
 *
 * @author pengling
 * @date 2014-12-2
 */
public class RadioPageView implements OnCheckedChangeListener {
    private View mainView;
    private RadioGroup mRadioGroup;
    private ImageView mImageView;
    private ScrollViewCustom mHorizontalScrollView;
    private MyViewPager mViewPager;
    private LinearLayout preIcon, endIcon;
    private List<Float> rdoList;
    private Activity activity;
    private OnClickListener itemOnClick;
    float mCurrentCheckedRadioLeft = 0;
    boolean isScanScroll;
    private List<View> mViews;

    // private List<File> fileList = new ArrayList<File>();
    // private View carrierView;// 页面载体

    public RadioPageView(View mainView, Activity activity,
                         OnClickListener itemOnClick, boolean isScanScroll) {
        this.isScanScroll = isScanScroll;
        this.mainView = mainView;
        this.activity = activity;
        this.itemOnClick = itemOnClick;
    }

    /**
     * 初始化控制器
     */
    public void iniController(List<View> mViews, List<String> radioButtonStrList) {
        this.mViews = mViews;
        float rdo1 = activity.getResources().getDimension(
                R.dimen.task_demand_main_radio);
        rdoList = new ArrayList<Float>();
        for (int i = 0; i < mViews.size(); i++) {
            rdoList.add(rdo1 * i);
        }
        preIcon = (LinearLayout) mainView.findViewById(R.id.preicon);
        endIcon = (LinearLayout) mainView.findViewById(R.id.endicon);
        mRadioGroup = (RadioGroup) mainView.findViewById(R.id.radioGroup);

        initRadioButton(radioButtonStrList);
        mImageView = (ImageView) mainView.findViewById(R.id.img1);
        mHorizontalScrollView = (ScrollViewCustom) mainView
                .findViewById(R.id.horizontalScrollView);
        mHorizontalScrollView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                mHorizontalScrollView.startScrollerTask();
                return false;
            }
        });
        mHorizontalScrollView.setOnScrollStopListner(new ScrollViewCustom.OnScrollStopListner() {
            public void onScrollToRightEdge() {
                preShow();
            }

            public void onScrollToMiddle() {
                doubleShow();
            }

            public void onScrollToLeftEdge() {
                endShow();
            }

            public void onScrollStoped() {
            }
        });
        mViewPager = (MyViewPager) mainView.findViewById(R.id.pager);
        mViewPager.setScanScroll(isScanScroll);
        mCurrentCheckedRadioLeft = getCurrentCheckedRadioLeft();// 更新当前蓝色横条距离左边的距离
        mRadioGroup.setOnCheckedChangeListener(this);
        mViewPager.setOnPageChangeListener(new MyPagerOnPageChangeListener());
        mViewPager.setAdapter(new MyPagerAdapter(mViews));// 设置ViewPager的适配器
    }

    /**
     * 动态添加radio
     *
     * @param radioButtonStrList
     */
    public void initRadioButton(List<String> radioButtonStrList) {
        System.out.println(radioButtonStrList);
        if (radioButtonStrList != null && radioButtonStrList.size() != 0) {
            for (int j = 0; j < radioButtonStrList.size(); j++) {
                RadioButton rdbtn = (RadioButton) LayoutInflater.from(activity)
                        .inflate(R.layout.task_demand_main_radiobtn, null);
                rdbtn.setId(j);
                rdbtn.setText(radioButtonStrList.get(j));
                mRadioGroup.addView(rdbtn, StringUtil.dip2px(activity, 80),
                        LinearLayout.LayoutParams.FILL_PARENT);
            }
        }
    }

    /**
     * 底部滑动块的最左边的块的显示与隐藏
     */
    public void preShow() {
        preIcon.setVisibility(View.VISIBLE);
        endIcon.setVisibility(View.INVISIBLE);
    }

    /**
     * 底部滑动块的最左最右边的块的隐藏
     */
    public void doubleShow() {
        preIcon.setVisibility(View.VISIBLE);
        endIcon.setVisibility(View.VISIBLE);
    }

    /**
     * 底部滑动块的最右边的块的显示与隐藏
     */
    public void endShow() {
        preIcon.setVisibility(View.INVISIBLE);
        endIcon.setVisibility(View.VISIBLE);
    }

    /**
     * ViewPager的PageChangeListener(页面改变的监听器)
     */
    public class MyPagerOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        /**
         * 滑动ViewPager的时候,让上方的HorizontalScrollView自动切换
         */
        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
                if (position == i) {
                    if (i == 0) {
                        endShow();
                    } else if (i == mRadioGroup.getChildCount() - 1) {
                        preShow();
                    } else {
                        doubleShow();
                    }
                    RadioButton rb = (RadioButton) mRadioGroup.getChildAt(i);
                    // if(rb.getText().toString().contains("附件")){
                    // mViewPager.setScanScroll(true);//带有横向拉出按钮操作的列表，不需左右切换页面。
                    // }else{
                    mViewPager.setScanScroll(isScanScroll);
                    // }
                    rb.performClick();
                }
            }
        }
    }

    public void setChecked(int i) {
        RadioButton rb = (RadioButton) mRadioGroup.getChildAt(i);
        rb.setChecked(true);
        mViewPager.setCurrentItem(i);// 让下方ViewPager跟随上面的HorizontalScrollView切换
    }

    /**
     * 获得当前被选中的RadioButton距离左侧的距离
     */
    public float getCurrentCheckedRadioLeft() {
        for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
            RadioButton rb = (RadioButton) mRadioGroup.getChildAt(i);
            if (rb.isChecked()) {
                return rdoList.get(i);
            }
        }
        return 0f;
    }

    /**
     * RadioGroup点击CheckedChanged监听
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        initData(checkedId);

        AnimationSet _AnimationSet = new AnimationSet(true);
        TranslateAnimation _TranslateAnimation = null;
        RadioButton rb = (RadioButton) mainView.findViewById(checkedId);
        System.out.println("-------" + rb.getText().toString());
        if (rb.getText().toString().contains("未开发")) {
            Toast.makeText(activity, "未开发", Toast.LENGTH_SHORT).show();
        } else {
            for (int i = 0; i < group.getChildCount(); i++) {
                RadioButton radioButton = (RadioButton) group.getChildAt(i);
                if (radioButton == rb) {
                    radioButton.setTextColor(activity.getResources().getColor(
                            R.color.white));
                    radioButton
                            .setBackgroundResource(R.drawable.style_border_line_right_gray_backblue);
                    _TranslateAnimation = new TranslateAnimation(
                            mCurrentCheckedRadioLeft, rdoList.get(i), 0f, 0f);
                    Constants.radioPageViewFlag = i;
                    mViewPager.setCurrentItem(i);// 让下方ViewPager跟随上面的HorizontalScrollView切换
                } else {
                    radioButton.setTextColor(activity.getResources().getColor(
                            R.color.font_deep_gray));
                    radioButton
                            .setBackgroundResource(R.drawable.style_border_line_right_gray);
                }
            }
        }

        if (_TranslateAnimation != null) {
            _AnimationSet.addAnimation(_TranslateAnimation);
            _AnimationSet.setFillAfter(true);
            _AnimationSet.setDuration(150);
            mImageView.bringToFront();
            mImageView.startAnimation(_AnimationSet);
            mCurrentCheckedRadioLeft = getCurrentCheckedRadioLeft();// 更新当前蓝色横条距离左边的距离
            mHorizontalScrollView.smoothScrollTo(
                    (int) mCurrentCheckedRadioLeft
                            - (int) activity.getResources().getDimension(
                            R.dimen.task_demand_main_radio), 0);
        }

    }

    /**
     * 初始化相应界面
     *
     * @param checkedId
     */
    public void initData(int checkedId) {

//	    File file = ((DemandMainActivity) activity).fileList.get(checkedId);
        File file = ((MyDemandActivity) activity).fileList.get(checkedId);
        BasicProperties maps = file.getMaps();
        BasicProperties thumbnall = file.getThumbnall();

        BasicProperties nullchecks = file.getNullchecks();
        boolean isCanEdit = true;// 是否可被编辑
        int radioPageFlag = 0;
        String prefix = "";
        if (nullchecks != null) {
            List<BasicProperties> tables = nullchecks.getTable();
            for (BasicProperties table : tables) {
                String tableName = table.getName();
                System.out.println("nullchecks:" + tableName + ","
                        + table.getPrefix());
            }
            if (!isCanEdit) {// 你无权限操作该页面，请处理完其他页面后再尝试进行操作
                Constants.isDialogBack = true;
                isAlertDown(activity, "你无权限操作该页面,请处理完<" + prefix
                        + ">页面后,再尝试进行操作!", "", "前往", radioPageFlag);
            }
        }
        // 含有子列表
        List<Item> itemList = file.getItem();// 子页面项
        View view = mViews.get(checkedId);
        DemandDKMapUtil demandDKMapUtil = new DemandDKMapUtil(activity);
        // 含有缩略图和图斑的 需刷新图层
        if ((maps != null && StringUtil.isNotEmpty(maps.getTitle()))
                || (thumbnall != null && StringUtil.isNotEmpty(thumbnall
                .getTitle()))) {

            demandDKMapUtil.refreshCheckTab(view, file);

            final MapControl mapControl = (MapControl) view
                    .findViewById(R.id.mapmain);
            if (mapControl != null) {
                /*
                 * added lzy 20150719 重新为mapControl设置地图内容
				 */
                System.out
                        .println("CommenUtil.getMap():" + CommenUtil.getMap());
                mapControl.setMap(CommenUtil.getMap());

                // add 杨宗仁 GPS信号显示
                TextView tv_info = (TextView) view.findViewById(R.id.info);
                tv_info.setTextColor(Color.BLACK);

                tv_info.setBackgroundColor(Color.argb(128, 255, 255, 255));
                try {
                    FactoryGPS factory = new FactoryGPS(tv_info, null, null,
                            null, mapControl);
                    FactoryGPS.NaviStart = false;
                    factory.StartStopGPS(activity, tv_info);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 刷新图层
                mapControl.Refresh();
            }
        }
        // 检测到当前页面包含ListView，则刷新List数据
        if (itemList != null && itemList.size() > 1) {
//			((DemandMainActivity) activity).initListData(file, view);
            ((MyDemandActivity) activity).initListData(file, view);
        }

    }

    public void isAlertDown(Context context, String str, String right,
                            String left, final int radioPosition) {
        final AlertDialog alertDialog = new AlertDialog(context, str, right,
                left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
            }

            @Override
            public void doCancel() {
                mViewPager.setCurrentItem(radioPosition);
                alertDialog.dismiss();
            }
        });
    }

}
